/**
 *  [[workflow集成]]
 *  示例：
 *  1. SRPC接收请求
 *  2. 向下游发送一个Http请求，并把Http的响应体返回给客户端
 */ 
#include <signal.h>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>

#include "example.srpc.h"
#include "workflow/WFFacilities.h"

using namespace srpc;
using std::string;

static WFFacilities::WaitGroup waitGroup{ 1 };

void sighandler(int)
{
	waitGroup.done();
}

class ExampleServiceImpl : public Example::Service
{
public:
	void Echo(EchoRequest *request, EchoResponse *response, srpc::RPCContext *ctx) override
	{
        // 1. 解析客户端的请求参数
        const string& message = request->message(); // getter
        const string& name = request->name();
        std::cout << "Request: { message=" << message
            << ", name=" << name << " }\n";

        // 2. 服务端的业务逻辑
        std::string url = "http://www.baidu.com";
        WFHttpTask* httpTask = WFTaskFactory::create_http_task(url, 3, 3, [response](WFHttpTask* task)
        {
            if (task->get_state() != WFT_STATE_SUCCESS) {
                response->set_message(string{"Error: "} + WFGlobal::get_error_string(task->get_state(), task->get_error()));
                return ;
            }
            // 获取响应体
            const void* data;
            size_t size;
            task->get_resp()->get_parsed_body(&data, &size);
            response->set_message((const char*)data);
        });

        // 3. 将httpTask放入SeriesWork中
        SeriesWork* series = ctx->get_series();
        series->push_back(httpTask);
	}
};

int main()
{
    // 注册信号处理函数
    signal(SIGINT, sighandler);

	SRPCServer server;

    // 添加服务
	ExampleServiceImpl service;
	server.add_service(&service);

    if (server.start(9527) == 0) {
        waitGroup.wait();
        server.stop();
    } else {
        std::cerr << "Error: start server failed!\n";
        std::exit(1);
    }

	return 0;
}
